package it.test.thread.utils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.*;
import java.util.function.Consumer;
import java.util.function.Function;

/**
 * @Copyright 纳新智能科技有限公司
 * @Author Liky
 * @Date 2023/8/17
 */
public class ThreadPoolUtils {
    private final ThreadPoolExecutor executor = new ThreadPoolExecutor(8,8,2, TimeUnit.SECONDS,new LinkedBlockingQueue<>());

    private final List<CompletableFuture> completableFutureList = new ArrayList<>();

    public void runList(List<String> taskList, Consumer<String> consumer){
        for(String task : taskList){
            CompletableFuture<Void> completableFuture = CompletableFuture.runAsync(() -> {
                consumer.accept(task);
            },executor);
            completableFutureList.add(completableFuture);
        }
        CompletableFuture futureAll = CompletableFuture.allOf(taskList.toArray(new CompletableFuture[0]));
        try {
            futureAll.get();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } catch (ExecutionException e) {
            throw new RuntimeException(e);
        } finally {
            executor.shutdown();
        }
    }
}
